package doc

import (
	mongo "beergo/lib/mongo"
	"beergo/lib/tool"
	"go.mongodb.org/mongo-driver/bson"
	mongo2 "go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"strings"
	"time"
)

type BaseDocument struct {
	IsEventBusOff bool `json:"-" bson:"-"`
}

func (this *BaseDocument) SetEventBusOn() {
	this.IsEventBusOff = false
}
func (this *BaseDocument) SetEventBusOff() {
	this.IsEventBusOff = true
}
func (this *BaseDocument) GetEventBusOff() bool {
	return this.IsEventBusOff
}

func GetMgo() *mongo.MgoStore {
	return mongo.GetMgo()
}

type BaseMgoStore struct {
}

func GetStore(collectionName string) *mongo2.Collection {
	mgo := GetMgo()
	return mgo.DB().Collection(collectionName)
}

func CreateFilter(filters map[string]interface{}) bson.D {
	//re := make(map[string]interface{})
	prepare := make(map[string][]bson.E)
	direct := make(bson.D,0)
	for key, filter := range filters {
		var value interface{}
		finds := strings.Split(key, "__")
		last := finds[len(finds)-1]
		//检查是否包含了特定的关键词
		//hasSuffix := 0
		if tool.IsInArray([]interface{}{"gt", "gte", "lt", "lte", "in", "nin", "eq", "ne", "exists", "near"}, last) > -1 {
			//hasSuffix = 1
			key = strings.ReplaceAll(key, "__"+last, "")
			value = tool.StringKeyMap{"$" + last: filter}
			key = strings.ReplaceAll(key, "__", ".")
			if strings.HasSuffix(key,"At") {
				filter,_ := time.Parse(time.RFC3339,filter.(string))
				prepare[key] = append(prepare[key],bson.E{"$" + last,filter})
			}else {
				prepare[key] = append(prepare[key],bson.E{"$" + last,filter})
			}
		} else {
			if key == "id" {
				key = "_id"
				value = bson.E{"$oid",value}
			} else {
				value = filter
			}
			key = strings.ReplaceAll(key, "__", ".")
			direct = append(direct ,bson.E{key,value})
		}
		//re[key] = value
	}
	for key, v := range prepare {
		direct = append(direct ,bson.E{key,v})
	}
	return direct
}

func CreateOption(orderby []string, offset int, limit int) *options.FindOptions {
	//tool.JsonLog(orderby)
	//处理排序数据
	realOrderBy := bson.D{}
	for _, str := range orderby {
		if str[0:1] == "-" || str[0:1] == "_" {
			realOrderBy = append(realOrderBy, bson.E{str[1:],-1})
		}else {
			realOrderBy = append(realOrderBy, bson.E{str,1})

		}
	}
	opt := options.FindOptions{}
	//tool.JsonLog(realOrderBy)
	return opt.SetLimit(int64(limit)).SetSkip(int64(offset)).SetSort(realOrderBy)
}

func CreateFindOneOption(orderby []string) *options.FindOneOptions {
	//处理排序数据
	realOrderBy := bson.D{}
	for _, str := range orderby {
		if str[0:1] == "-" || str[0:1] == "_" {
			realOrderBy = append(realOrderBy, bson.E{str[1:],-1})
		}else {
			realOrderBy = append(realOrderBy, bson.E{str,1})
		}
	}
	opt := options.FindOneOptions{}

	return opt.SetSort(realOrderBy)
}
